package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.qk.common.constant.CacheConstants;
import com.qk.domain.business.BusinessCountDO;
import com.qk.domain.clue.ClueCountDO;
import com.qk.management.aop.anno.ReportAnno;
import com.qk.management.mapper.BusinessMapper;
import com.qk.management.mapper.ClueMapper;
import com.qk.management.service.ReportOverviewService;
import com.qk.vo.portal.PortalVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @Author ZgYn
 * @Date 2025/10/15 14:53
 * @Name ReportOverviewServiceImpl
 */
@Slf4j
@Service
public class ReportOverviewServiceImpl implements ReportOverviewService {
    @Autowired
    private ClueMapper clueMapper;
    @Autowired
    private BusinessMapper businessMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;



    @Override
    @ReportAnno(keyPrefix = CacheConstants.REPORT_OVERVIEW_KEY_PREFIX
            , expireTime = 24*60L
            , expireTimeUnit = TimeUnit.MINUTES
    )

    public PortalVO overview() {
        ClueCountDO clueCountDO = clueMapper.selectCountClue();

        BusinessCountDO businessCountDO = businessMapper.selectCountBusiness();
        PortalVO portalVO = BeanUtil.copyProperties(clueCountDO, PortalVO.class);
        BeanUtil.copyProperties(businessCountDO, portalVO);
        return portalVO;
    }


    @Override
    public PortalVO overviewByRedis() {
        String redisKey = CacheConstants.REPORT_OVERVIEW_KEY_PREFIX + "reportOverview";
        String jsonStr = null;
        try {
            jsonStr = redisTemplate.opsForValue().get(redisKey);
            if (ObjectUtil.isNotEmpty(jsonStr)) {
                PortalVO vo = JSONUtil.toBean(jsonStr, PortalVO.class);
                return vo;
            }
        } catch (Exception e) {
            log.error("查询缓存异常", e);
        }
        ClueCountDO clueCountDO = clueMapper.selectCountClue();
        BusinessCountDO businessCountDO = businessMapper.selectCountBusiness();
        PortalVO vo = BeanUtil.copyProperties(clueCountDO, PortalVO.class);
        BeanUtil.copyProperties(businessCountDO, vo);
        try {
            String json = JSONUtil.toJsonStr(vo);
            redisTemplate.opsForValue().set(redisKey, json);
        } catch (Exception e) {
            log.error("添加缓存异常", e);
        }
        return vo;
    }
}
